package com.lingdong.onlinejudge.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.lingdong.onlinejudge.model.dto.submit.JudgeInfo;
import com.lingdong.onlinejudge.model.dto.topic.JudgeCase;
import com.lingdong.onlinejudge.model.dto.topic.JudgeConfig;
import com.lingdong.onlinejudge.model.entity.Topic;
import com.lingdong.onlinejudge.model.enums.JudgeInfoMessageEnum;

import java.util.List;

public class DefaultJudgeStrategy implements JudgeStrategy{
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();

        Long time = judgeInfo.getTime();
        Long memory = judgeInfo.getMemory();

        JudgeInfo judgeInfoResult = new JudgeInfo();
        judgeInfoResult.setTime(time);
        judgeInfoResult.setMemory(memory);

        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        Topic topic = judgeContext.getTopic();
        List<JudgeCase> judgeCases = judgeContext.getJudgeCaseList();

        JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.Accepted;
        // 校验结果是否正确
        if (outputList.size() != inputList.size()){
            judgeInfoMessageEnum = JudgeInfoMessageEnum.Wrong_Answer;
            judgeInfoResult.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResult;
        }
        for (int i = 0; i < judgeCases.size(); i++) {
            JudgeCase judgeCase = judgeCases.get(i);
            if (!judgeCase.getOutput().equals(outputList.get(i))){
                judgeInfoMessageEnum = JudgeInfoMessageEnum.Wrong_Answer;
                judgeInfoResult.setMessage(judgeInfoMessageEnum.getValue());
                return judgeInfoResult;
            }
        }
        // 判断题目的限制是否符合要求
        String judgeConfigStr = topic.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        Long needTimeLimit = judgeConfig.getTimeLimit();
//        Long needMemoryLimit = judgeConfig.getMemoryLimit();
//        if (memory > needMemoryLimit){
//            judgeInfoMessageEnum = JudgeInfoMessageEnum.Memory_Limit_Exceeded;
//            judgeInfoResult.setMessage(judgeInfoMessageEnum.getValue());
//            return judgeInfoResult;
//        }
        if (time > needTimeLimit){
            judgeInfoMessageEnum = JudgeInfoMessageEnum.Time_Limit_Exceeded;
            judgeInfoResult.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResult;
        }
        judgeInfoResult.setMessage(judgeInfoMessageEnum.getValue());
        judgeInfoResult.setTime(time);
        judgeInfoResult.setSuccess(true);
        return judgeInfoResult;
    }
}
